<?php
namespace app\controller\admin;

use app\BaseController;
use app\Code;
use app\dao\UserDao;
use app\model\UserModel;
use app\validate\AddUserValidate;
use think\exception\ValidateException;
use think\facade\Request;

class UserController extends BaseController
{
    public function addUser()
    {
        // 获取请求数据
            $data = Request::only(['username', 'password', 'real_name', 'role']);

        // 验证参数
        try {
            validate(AddUserValidate::class)->scene('add')->check($data);
        } catch (ValidateException $e) {
            return $this->returnJson([], Code::UNPROCESSABLE_ENTITY, $e->getMessage());
        }

        // 检查用户名是否已存在
        $existingUser = (new UserDao())->getUserByUsername($data['username']);
        if ($existingUser) {
            return $this->returnJson([], Code::FORBIDDEN, '用户名已存在');
        }

        // 创建用户
        $userData = [
            'username' => $data['username'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'real_name' => $data['real_name'],
            'role' => $data['role']
        ];

        $user = (new UserDao())->createUser($userData);

        if (!$user) {
            return $this->returnJson([], Code::SERVER_ERROR, '用户创建失败');
        }

        // 返回创建的用户信息（不包含密码）
        return $this->returnJson([
            'id' => $user->id,
            'username' => $user->username,
            'real_name' => $user->real_name,
            'role' => $user->role
        ]);
    }
}